__author__ = 'Ion Luo'
# -*- coding: utf-8 -*-
import itchat
import datetime
import json
import xlwt

# 获取群的username，对群成员进行分析需要用到
# 显示所有的群聊信息，默认是返回保存到通讯录中的群聊
def getroom_message(n):
    itchat.dump_login_status()
    RoomList = itchat.search_chatrooms(name=n)
    if RoomList is None:
        pass
    else:
        return RoomList[0]['UserName']


# 获取群聊列表
def getchatrooms():
    roomslist = itchat.get_chatrooms()
    return roomslist


def write_txt(chatRoomsList):
    with open('群用户名.txt', 'w', encoding='utf-8') as f:
        text = "你一共加入了{}群".format(str(len(chatRoomsList)))
        for room in chatRoomsList:
            text += '\r\n------------------------------群名称：{}, 该微信群一共有{}个成员"----------------------------------\r\n'\
                .format(room['name'], str(room['memberNum']))

            for i in room['memberList']:
                # HeadImgUrl Sex Signature DisplayName IsOwner ContactFlag UserName
                text += '省份：'+i['Province']+" NickName为："+i['NickName']+" RemarkName为："+i['RemarkName']+'\n'

        text += json.dumps(chatRoomsList)
        f.write(text)


def set_style(name, height, bold=False):
    style = xlwt.XFStyle()  # 初始化样式

    font = xlwt.Font()  # 为样式创建字体
    font.name = name  # 'Times New Roman'
    font.bold = bold
    font.color_index = 4
    font.height = height

    # borders= xlwt.Borders()
    # borders.left= 6
    # borders.right= 6
    # borders.top= 6
    # borders.bottom= 6

    style.font = font
    # style.borders = borders

    return style


def write_excel(chatRoomsList):
    f = xlwt.Workbook()  # 创建工作簿
    for room in chatRoomsList:
        sheet = f.add_sheet(room['name'], cell_overwrite_ok=True)  # 创建sheet
        header = [u'省份', u'NickName', u'RemarkName', u'HeadImgUrl', u'Sex', u'Signature', u'DisplayName', u'IsOwner', u'Name']
        # 生成第一行
        for index, item in enumerate(header):
            sheet.write(0, index, item, set_style('Times New Roman', 220, True))
        for index, item in enumerate(room['memberList']):
            sheet.write(index + 1, 0, item['Province'])
            sheet.write(index + 1, 1, item['NickName'])
            sheet.write(index + 1, 2, item['RemarkName'])
            sheet.write(index + 1, 3, item['HeadImgUrl'])
            sheet.write(index + 1, 4, item['Sex'])
            sheet.write(index + 1, 5, item['Signature'])
            sheet.write(index + 1, 6, item['DisplayName'])
            sheet.write(index + 1, 7, item['IsOwner'])
            sheet.write(index + 1, 8, item['name'])
    f.save('weChat.xlsx')  # 保存文件


if __name__ == '__main__':
    # itchat.auto_login()
    itchat.auto_login(hotReload=True)
    print("程序开始：", datetime.datetime.now())

    roomsList = []
    for i in getchatrooms():
        roomsList.append(i['NickName'])

    data = {"roomsNum": len(roomsList), "chatRoomsList": []}

    for n in roomsList:
        ChatRoom = itchat.update_chatroom(getroom_message(n), detailedMember=True)
        room = {
            "name": ChatRoom['NickName'],
            "memberNum": len(ChatRoom['MemberList']),
            "memberList": ChatRoom['MemberList']
        }
        data['chatRoomsList'].append(room)

    write_txt(data['chatRoomsList'])
    write_excel(data['chatRoomsList'])
    print("程序结束：", datetime.datetime.now())